package edu.software.PBL_Management_System.controller;

import edu.software.PBL_Management_System.entity.User;
import edu.software.PBL_Management_System.service.EmailService;
import edu.software.PBL_Management_System.service.UserService;
import edu.software.PBL_Management_System.util.IdEncryptionUtil;
import edu.software.PBL_Management_System.util.VerificationCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private VerificationCodeUtil verificationCodeUtil;

    @Autowired
    private IdEncryptionUtil idEncryptionUtil;

    /**
     *用户登录
     * @param account  //用户名或邮箱
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String account, @RequestParam String password) {
        Map<String, Object> result = new HashMap<>();
        //返回给前端一个Json数组，success表示是否请求成功，message表示请求结果信息

        try {
            User user = userService.login(account, password);

            if (user != null) {
                // 用户存在，登录成功
                log.info("用户登录: {}", user.getUsername()); //控制台输出信息

                // 加密用户ID
                String encryptedId = idEncryptionUtil.encryptId(user.getId());

                result.put("success", true);
                result.put("message", "登录成功");
                result.put("user", user);
                result.put("encryptedId", encryptedId);
            } else {
                // 用户不存在或密码错误
                result.put("success", false);
                result.put("message", "账号或密码错误");
            }
        } catch (Exception e) {
            // 处理异常
            log.error("登录验证失败: {}", e.getMessage()); //控制台输出错误信息
            result.put("success", false);
            result.put("message", "登录验证失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 发送邮箱验证码
     * @param params 包含账号的参数
     * @return 结果
     */
    @PostMapping("/api/sendVerificationCode")
    public Map<String, Object> sendVerificationCode(@RequestBody Map<String, String> params) {
        String account = params.get("account");
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证邮箱格式,
            //TODO: 目前只支持邮箱登录
            if (!account.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
                result.put("success", false);
                result.put("message", "请输入正确的邮箱格式");
                return result;
            }

            // 生成验证码
            String code = verificationCodeUtil.generateCode();
            log.info("为邮箱 {} 生成验证码: {}", account, code);

            // 发送验证码邮件
            boolean sendResult = emailService.sendVerificationCode(account, code);

            if (sendResult) {
                // 保存验证码
                verificationCodeUtil.saveCode(account, code);

                // 查询用户是否存在
                User user = userService.emailOrPhoneLogin(account);

                result.put("success", true);
                result.put("message", "验证码发送成功");
                result.put("expireTime", verificationCodeUtil.getExpireTime());

                // 如果用户不存在，不返回用户信息
                if (user != null) {
                    result.put("userExists", true);
                } else {
                    result.put("userExists", false);
                }
            } else {
                result.put("success", false);
                result.put("message", "验证码发送失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("发送验证码失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "发送验证码失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 验证码登录
     * @param params 包含账号和验证码的参数
     * @return
     */
    @PostMapping("/api/verifyCodeLogin")
    public Map<String, Object> verifyCodeLogin(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();

        String account = params.get("account");
        String verificationCode = params.get("verificationCode");

        try {
            // 验证验证码
            boolean verifyResult = verificationCodeUtil.verifyCode(account, verificationCode);

            if (verifyResult) {
                // 验证码正确，查询用户
                User user = userService.emailOrPhoneLogin(account);

                if (user == null) {
                    // 用户不存在，自动创建用户
                    log.info("新增用户");
                    user = new User();
                    user.setEmail(account);
                    user.setUsername("新用户：" + account);
                    user.setPassword(""); // TODO:使用验证码登录用户目前没有密码
                    String userType = params.get("userType");
                    if (userType != null && !userType.isEmpty()) {
                        user.setUsertype(userType);  // 设置用户类型
                    }
                    else {
                        user.setUsertype("publisher"); //  默认为发布者
                    }

                    try {
                        userService.save(user);
                        log.info("用户创建成功，ID: {}", user.getId());

                        // 重新获取保存的用户以确保有ID
                        user = userService.emailOrPhoneLogin(account);
                        if (user == null || user.getId() == null) {
                            throw new RuntimeException("用户创建后未找到或ID为空");
                        }
                    } catch (Exception e) {
                        log.error("用户创建失败: {}", e.getMessage());
                        throw new RuntimeException("用户创建失败: " + e.getMessage());
                    }
                }

                // 加密用户ID
                String encryptedId = idEncryptionUtil.encryptId(user.getId());

                result.put("success", true);
                result.put("message", "登录成功");
                result.put("user", user);
                result.put("encryptedId", encryptedId);
            } else {
                result.put("success", false);
                result.put("message", "验证码错误或已过期");
            }
        } catch (Exception e) {
            log.error("验证码登录失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "验证码登录失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 修改密码操作
     * @param params 包含账号和验证码的参数
     * @return
     */
    @Transactional
    @PostMapping("/api/changePassword")
    public Map<String, Object> changePassword(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();

        String account = params.get("account");
        String verificationCode = params.get("verificationCode");

        try {
            // 参数校验
            if (account == null || account.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "账号不能为空");
                return result;
            }

            if (verificationCode == null || verificationCode.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "验证码不能为空");
                return result;
            }

            // 验证验证码
            boolean verifyResult = verificationCodeUtil.verifyCode(account, verificationCode);

            if (!verifyResult) {
                result.put("success", false);
                result.put("message", "验证码错误或已过期");
                return result;
            }

            // 验证码正确，查询用户
            User user = userService.emailOrPhoneLogin(account);

            if (user == null) {
                // 用户不存在 - 关键修复点：这里必须返回结果
                log.error("用户不存在，账号：{}", account);
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }

            // 获取新密码和确认密码
            String newPassword = params.get("newPassword");
            String confirmPassword = params.get("confirmPassword");

            // 参数校验
            if (newPassword == null || newPassword.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "新密码不能为空");
                return result;
            }

            if (confirmPassword == null || confirmPassword.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "确认密码不能为空");
                return result;
            }

            // 校验两次密码是否一致
            if (!newPassword.equals(confirmPassword)) {
                result.put("success", false);
                result.put("message", "两次输入的密码不一致");
                return result;
            }

            // 密码强度校验（可选，建议添加）
            if (newPassword.length() < 6) {
                result.put("success", false);
                result.put("message", "密码长度不能少于6位");
                return result;
            }

            // 设置并保存新密码
            user.setPassword(newPassword);
            userService.save(user);

            log.info("用户{}修改密码成功", account);
            result.put("success", true);
            result.put("message", "密码修改成功");
            // 注意：不要返回用户完整信息，避免敏感数据泄露
            // result.put("user", user);

        } catch (Exception e) {
            log.error("修改密码失败，账号：{}，错误信息：{}", account, e.getMessage(), e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        }

        return result;
    }
}